package com.tb.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tb.mapper.MessageMapper;
import com.tb.model.Message;
import com.tb.model.MessageExample;
import com.tb.model.PageBean;
import com.tb.model.User;
import com.tb.util.MyConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @description:
 * @author: wangguichun
 * @create: 2018-04-16 20:05
 **/

@Service
public class MessageService {

    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private QuestionService questionService;
    @Autowired
    private AnswerService answerService;
    @Autowired
    private QCommentService qCommentService;
    @Autowired
    private ACommentService aCommentService;


    public PageInfo<Message> getMessageByToIdAndPageId(int toId, Integer pageId) {
        //按接收者Id和时间降序获得消息列表
        MessageExample example = new MessageExample();
        example.setOrderByClause("time desc");
        MessageExample.Criteria criteria = example.createCriteria();
        criteria.andToIdEqualTo(toId);

        PageHelper.startPage(pageId, MyConstant.PAGE_SIZE_MESSAGE);
        List<Message> messages = messageMapper.selectByExample(example);
        //为消息注入发送者，消息内容
        for (Message message : messages) {
            Integer fromId = message.getFromId();
            User user = userService.getUserById(fromId);
            message.setFromUser(user);
            Integer objectId = message.getObjecId();
            String content = "";
            switch (message.getType()) {
                case MyConstant.ACT_COMMENT_QUES:
                case MyConstant.ACT_ANSWER:
                case MyConstant.ACT_COMMENT_ANS:
                case MyConstant.ACT_STAR:content = questionService.getQuestionById(objectId).getTitle();break;
            }
            message.setContent(content);
        }

        return new PageInfo<>(messages);
    }

    public void addMessage(Message message) {
        messageMapper.insertSelective(message);
    }

    public void removeRecordByTypeAndObjectId(byte type, int objectId) {
        MessageExample example = new MessageExample();
        MessageExample.Criteria criteria = example.createCriteria();
        criteria.andTypeEqualTo(type);
        criteria.andObjecIdEqualTo(objectId);
        messageMapper.deleteByExample(example);
    }
}
